package top.kiterunner.learning.concurrency_test;

/**
 * AdorynZhao in Tencent-UESTC.
 * Source Code Created on 2017/7/3.
 * 问题：同步方法和非同步方法能否同时被调用？？？
 */
public class ThreadDemo2 {

    public synchronized void method1() {
        System.out.println(Thread.currentThread().getName() + " M1 Starting...");
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(Thread.currentThread().getName() + " M1 Ending...");
    }

    public void method2() {
        System.out.println(Thread.currentThread().getName() + " M2 Starting...");
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + " M2 Ending...");
    }

    // 测试方法：启动两个线程，一个线程执行同步方法，一个线程执行非同步方法，方法内执行Sleep操作
    // 测试标准：如果两个线程能够同时睡眠，则表示可以同时调用同步方法和非同步方法
    public static void main(String[] args) {
        final ThreadDemo2 t2 = new ThreadDemo2();

        // Java8 lambda表达式
        new Thread(()->t2.method1(), "Thread_1").start();
        new Thread(()->t2.method2(), "Thread_2").start();

        // 基于接口
        new Thread(new Runnable() {
            @Override
            public void run() {
                t2.method1();
            }
        }, "Thread_1").start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                t2.method2();
            }
        }, "Thread_2").start();

        new Thread(t2::method1, "Thread_1").start();
        new Thread(t2::method2, "Thread_2").start();
    }
}
